<template>
  <div class="gift-code-upload">
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :before-upload="beforeUpload"
      :on-change="handleChange"
      :auto-upload="false"
      multiple
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList"
    >
      <el-button size="small" type="primary">选择文件</el-button>
      <div slot="tip" class="el-upload__tip">
        只能上传.txt文件，每条换行区分<template
          v-if="totalNum"
        >，当前已上传 <strong style="color: red">{{ totalNum }}</strong> 条数据</template>
      </div>
    </el-upload>
    <div />
  </div>
</template>
<script>
export default {
  props: {
    prop: {
      type: String,
      default: ''
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  computed: {
    totalNum: {
      get(val) {
        return this.data[this.prop] && this.data[this.prop].split(',').length
      },
      set(val) {
        console.log('new', val)
      }
    }
  },
  data() {
    return {
      fileList: []
    }
  },
  methods: {
    clear() {
      this.fileList = []
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`)
    },
    async beforeRemove(file, fileList) {
      const res = await this.$confirm(`确定移除 ${file.name}？`)
      if (res) {
        this.fileList = this.fileList.filter(f => f.name !== file.name)
      }
      return res
    },
    beforeUpload(file) {
      const { type } = file
      if (type !== 'text/plain') {
        this.$message.error('上传的文件必须为txt类型!')
        return Promise.reject()
      }
      return true
    },
    handleChange(file, fileList) {
      const { type } = file.raw
      if (type !== 'text/plain') {
        this.$message.error('上传的文件必须为txt类型!')
        this.fileList = []
        return
      }
      this.fileList = fileList
      const reader = new FileReader()
      reader.onload = () => {
        if (reader.result) {
          const res = reader.result.replace(/\r\n/g, ',')
          this.totalNum = res.length || 0
          this.prop && this.$set(this.data, this.prop, res)
        }
      }
      reader.readAsText(file.raw)
    },
    submit() {
      if (this.fileList.length !== 1) {
        return ''
      }
      return this.fileList[0].raw
    }
  }
}
</script>
<style lang="scss">
.gift-code-upload {
  .el-upload-list {
    padding: 0;
  }
}
</style>
